<template>
  <el-dialog
    v-model="visibility"
    title="提货"
    width="90%"
    top="2vh"
    append-to-body
    draggable
    :close-on-click-modal="false">
    <div class="wait-delivery-dialog">
      <div class="fix-box">
        <el-form
          :model="topFormData"
          class="search_form">
          <div style="display: flex;justify-content: space-between;">
            <!-- <span class="sonTitle">计算结果</span> -->
          </div>
          <div class="card-box">
            <el-card class="left-top">
              <div class="card-title">物流信息</div>
              <el-row class="searchForm" style="margin-top: 30px;">
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="商品名称：">
                    {{ formData.goodsName }}
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="司机名字：">
                    {{ formData.driverName }}
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="车牌号：">
                    {{ formData.carNumber }}
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="购买吨数：">
                    <el-tag type="primary">
                      {{ formData.buyTon || 0 }}
                    </el-tag>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="剩余吨数：">
                    <el-tag type="primary">
                      {{ formData.residueTon || 0 }}
                    </el-tag>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="备注信息：">
                    <el-tooltip
                      :content="formData.remark"
                      placement="top">
                      <span class="truncate-text">{{ formData.remark }}</span>
                    </el-tooltip>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card class="left-bottom">
              <div class="card-title">计算结果</div>
              <el-row class="searchForm"  style="margin-top: 30px;">
                <el-col
                  :span="8"
                  class="el_col_fit first-item">
                  <el-form-item label="提货单价：">
                    {{ countInfo.pickUnitPrice || 0 }} 元
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="采购总价：">
                    {{ countInfo.pickTotalPrice || 0 }} 元
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="仓储服务费：">
                    {{ countInfo.warehouseServicePrice || 0 }} 元
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit first-item">
                  <el-form-item
                    label="手动-预付款："
                    prop="manualCompanyFirstPayPrice">
                    <el-input-number
                      v-model="formData.manualCompanyFirstPayPrice"
                      placeholder="请输入"
                      :precision="2"
                      :min="0"
                      controls-position="right"
                      style="width: 150px;"
                      clearable></el-input-number> 元
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="计算-我司预付款：">
                    {{ countInfo.pickCompanyFirstPayPrice || 0 }} 元
                  </el-form-item>
                </el-col>
                <el-col
                  :span="8"
                  class="el_col_fit">
                  <el-form-item label="实际抵扣-我司预付款：">
                    {{ countInfo.sumCompanyFirstPayPrice || 0 }} 元
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card class="right">
              <div class="card-title">采购订单</div>
              <div class="right-item">
                <div class="right-title">已付-预付款：</div>
                <div class="right-main">{{ infoData.pricePaidFirstPrice || 0 }} 元</div>
              </div>
              <div class="right-item">
                <div class="right-title">已抵扣-预付款：</div>
                <div class="right-main">{{ infoData.priceSumCompanyFirstPayPrice || 0 }} 元</div>
              </div>
              <div class="right-item">
                <div class="right-title">剩余待抵扣-预付款：</div>
                <div class="right-main">{{ infoData.priceRemainFirstPrice || 0 }} 元</div>
              </div>
            </el-card>
          </div>
        </el-form>
      </div>
      <div class="auto-box">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          :label-width="config.form.label.width"
          status-icon>
          <el-row class="searchForm mid-search">
            <el-col
              :span="8"
              class="el_col_fit">
              <el-form-item
                label="提货日期"
                prop="pickDate">
                <el-date-picker
                  v-model="formData.pickDate"
                  placeholder="提货日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col
              :span="8"
              class="el_col_fit">
              <el-form-item
                label="提破损吨数"
                prop="pickWornTon">
                <el-input-number
                  v-model="formData.pickWornTon"
                  clearable
                  width="100%"
                  :precision="3"
                  :min="0"
                  controls-position="right"
                  placeholder="提破损吨数"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col
              :span="8"
              class="el_col_fit">
              <el-form-item
                label="提完整吨数"
                prop="pickIntactTon">
                <el-input-number
                  v-model="formData.pickIntactTon"
                  clearable
                  width="100%"
                  :precision="3"
                  :min="0"
                  controls-position="right"
                  placeholder="提完整吨数"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row class="top_search">
          <el-form-item label="采购订单名称">
            <el-input
              v-model="topFormData.purchaseOrderName"
              clearable
              style="width: 150px"
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input
              v-model="topFormData.baseRiceBarnGoodsSimpleName"
              clearable
              style="width: 150px"
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-button
            type="primary"
            style="margin-left: 10px"
            @click="getList(topFormData)">
            <template #icon>
              <el-icon>
                <search />
              </el-icon>
            </template>
            {{ config.button.text.query }}
          </el-button>
        </el-row>
        <el-table
          :data="tableData"
          border="1"
          ref="tableRef"
          max-height="400"
          @selection-change="handleSelectionChange"
          v-loading="tableLoading">
          <el-table-column
            type="selection"
            width="40"
            align="center" />
          <el-table-column
            prop="baseCapitalWarehouseName"
            label="资金仓库名称"
            width="130"
            :resizable="false" />
          <el-table-column
            prop="baseRiceBarnSimpleName"
            label="米厂名称"
            :resizable="false" />
          <el-table-column
            prop="purchaseOrderName"
            label="采购订单名称"
            :resizable="false" />
          <el-table-column
            prop="trainNumber"
            label="车次号"
            :resizable="false" />
          <el-table-column
            prop="baseRiceBarnGoodsSimpleName"
            label="商品名称"
            :resizable="false" />
          <el-table-column
            prop="region"
            label="商品地区"
            :resizable="false" />
          <el-table-column
            prop="arriveDate"
            label="到货日期"
            width="130"
            :resizable="false">
            <template #default="scope">
              {{ formatDate(scope.row.arriveDate) }}
            </template>  
          </el-table-column>
          <el-table-column
            prop="residueWornTon"
            label="剩余-破损吨数"
            :resizable="false" />
          <el-table-column
            prop="residueIntactTon"
            label="剩余-完整吨数"
            :resizable="false" />
        </el-table>
        <Pagination
          :pageNum="pageNum"
          :pageSize="[5,20,50]"
          :total="total"
          @handle-size-change="(val) => pageSize = val"
          @handle-current-change="(val) => pageNum = val" />
      </div>
    </div>
    <template #footer>
      <div>
        <el-button
          type="warning"
          @click="calculatePrice">
          计算价格
        </el-button>
        <el-button
          type="success"
          @click="confirmDelivery">
          确认提货
        </el-button>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import Pagination from "@/components/Pagination.vue"
import Table from "@/components/Table.vue"
import config from "@/common/element-plus/config";
import ApiBaseCompany from "@/api/modules/base-company"
import { useValidator } from "@/hooks/useValidator";
import ApiTrainRepertory from "@/api/modules/train-repertory"
import { useTable } from "@/hooks/useTable"
import message from "@/common/element-plus/message";
import { ElMessageBox } from "element-plus";
import ApiTrainPickRecord from "@/api/modules/train-pickRecord"
import { formatDate,formatDateTime,getCurrentDate } from "@/common/utils/date";

const visibility = ref(false)
const topFormData = ref({})
const formData = ref({})
const infoData = ref({})
const logisticsInfo = ref({})
const formRef = ref()
const tableRef = ref()
const { required, validate, clearValidate } = useValidator()
const countInfo = ref({})


const { tableMethods, tableState, pagination } = useTable({
  fetchDataApi: async (data) => {
    const { pageSize, pageNum } = pagination
    if (props.rowData?.baseCapitalWarehouseId){
      data = {
        ...data,
        isPickQuery: true,
        baseCapitalWarehouseId: props.rowData?.baseCapitalWarehouseId||"",
        baseRiceBarnGoodsSimpleName: topFormData.value.baseRiceBarnGoodsSimpleName
      }
      const res = await ApiTrainRepertory.selectPage(data, {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
      })
      return {
        list: res.data.records,
        total: res.data.total
      }
    }
  }
})
const { getList } = tableMethods
const { pageSize, pageNum } = pagination
const { total, tableLoading, tableData } = tableState

// 选中行的数据
const selectedRow = ref(null);

// 处理选中行变化
const handleSelectionChange = async(rows) => {
  if (rows.length > 1) {
    // 如果选中了多行，则只保留最后一行
    const lastRow = rows[rows.length - 1];
    tableRef.value?.clearSelection(); // 清空所有选中状态
    tableRef.value?.toggleRowSelection(lastRow, true); // 重新选中最后一行
    selectedRow.value = lastRow;
  } else {
    selectedRow.value = rows[0] || null;
  }
  if (selectedRow.value){
    const infoRes = await ApiTrainPickRecord.getCreditInfo(selectedRow.value.purchaseOrderNumber);
    infoData.value = infoRes.data;
  } else {
    infoData.value={}
  }
};

const formRules = {
  pickDate: [required("提货日期")],
  pickWornTon: [required("提破损吨数")],
  pickIntactTon: [required("提完整吨数")],
  manualCompanyFirstPayPrice: [required("手动-预付款")],
}

const props = defineProps(["rowData"])

const emits = defineEmits(["save"])

watch(() => visibility.value, (newVal) => {
  if (newVal) {
    formData.value = { ...props.rowData,pickDate: getCurrentDate(),manualCompanyFirstPayPrice: 0 };
    topFormData.value.baseRiceBarnGoodsSimpleName = formData.value.goodsName
    getList()
    setTimeout(() => {
      clearValidate(formRef.value);
      const dialogBody = document.querySelector(".el-dialog__body");
      dialogBody.style.maxHeight = "80vh";
    });
  }
}, { immediate: true });



const confirmDelivery = async() => {
  if (selectedRow.value){
    await validate(formRef.value)
    ElMessageBox.confirm("确定要提货吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            trainRepertoryId: selectedRow.value.id,
            logisticsRecordId: formData.value.id,
            pickDate: formData.value.pickDate,
            pickIntactTon: formData.value.pickIntactTon,
            pickWornTon: formData.value.pickWornTon,
            manualCompanyFirstPayPrice: formData.value.manualCompanyFirstPayPrice
          }
          const res  = await ApiTrainPickRecord.calculateConfirm(params);
          if (res?.success){
            await getList()
            if (Array.isArray(tableData.value)&&tableData.value.length>0){
              formData.value.pickWornTon="";
              formData.value.pickIntactTon="";
              formData.value.manualCompanyFirstPayPrice="";
            } else {
              visibility.value=false;
            }
          }
        })
        .catch(() => {
          // 用户点击了取消按钮
        });
  } else {
    message.warning("请先选择一条数据！");
  }
}

const calculatePrice = async() => {
  if (selectedRow.value){
    await validate(formRef.value)
    const params = {
      trainRepertoryId: selectedRow.value.id,
      logisticsRecordId: formData.value.id,
      pickDate: formData.value.pickDate,
      pickIntactTon: formData.value.pickIntactTon,
      pickWornTon: formData.value.pickWornTon,
      manualCompanyFirstPayPrice: formData.value.manualCompanyFirstPayPrice
    }
    const res  = await ApiTrainPickRecord.calculatePrice(params);
    countInfo.value = res.data
  } else {
    message.warning("请先选择一条数据！");
  }
}

defineExpose({ visibility })
</script>

<style lang="scss" scoped>
.el-row {
  align-items: flex-start;
}
:deep(.el-form-item__label) {
  width: 200px !important;
}
.sonTitle{
  font-weight: bold;
  font-size: 18px;
  margin-top: 10px;
  margin-bottom: 5px;
}
:deep(.searchForm){
  margin-top: 5px;
  .el-form-item__label{
    width: 100px !important;
  }
}

.top_search{
  background: rgb(235.9,245.3,255);
  padding: 10px 0;
  margin-top: 10px;
  :deep(.el-input__wrapper){
    background: rgb(235.9,245.3,255);
  }
  :deep(.el-form-item__label){
    width: 100px !important;
  }
  :deep(.el-form-item){
    margin: 0;
  }
}
:deep(.el-table__header){
  background: rgb(235.9,245.3,255) !important;
  th{
    background: rgb(235.9,245.3,255) !important;
  }
}

.mid-search{
  //background: rgb(205.9, 223, 304);
  background: rgb(235.9,245.3,255);
  padding: 10px 0;
  :deep(.el-input__wrapper){
    background: rgb(235.9,245.3,255);
  }
  :deep(.el-form-item){
    margin-bottom: 0;
  }
}

.card-box{
  display: grid;
  grid-template-columns: 80% 20%; /* 左边 70%，右边 30% */
  grid-template-rows: 53% 48%; /* 左边两个 div 各占 50% 高度 */
  height: 230px; /* 设置容器高度 */
  gap: 5px; /* 间距 */
  :deep(.el-card__body){
    width: 100%;
  }
  .el-card{
    box-sizing: border-box;
    position: relative;
    display: flex;
    align-items: center;
  }
  .left-top {
    grid-column: 1 / 2; /* 第一列 */
    grid-row: 1 / 2; /* 第一行 */
    background-color: #E8F5E9; /* 浅绿色 */
  }
  .left-bottom {
    grid-column: 1 / 2; /* 第一列 */
    grid-row: 2 / 3; /* 第二行 */
    background-color: #FFF9C4; /* 浅黄色 */
    :deep(.el-input__wrapper){
      background: #FFF9C4;
    }
    :deep(.el-form-item__label){
      width: 180px !important;
    }
    .first-item{
      :deep(.el-form-item__label){
        width: 130px !important;
      }
    }
    :deep(.el-input-number__increase){
      background: #FFF9C4;
    }
    :deep(.el-input-number__decrease){
      background: #FFF9C4;
    }
  }

  .right {
    grid-column: 2 / 3; /* 第二列 */
    grid-row: 1 / 3; /* 跨两行 */
    background-color: #C0F0F6; /* 深绿色 */
    font-size: 16px;
    
    :deep(.el-card__body){
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .right-item{
        display: flex;
        align-items: end;
        .right-title{
          color: #606266;
          min-width: 150px;
          text-align: right;
        }
        .right-main{
          margin-left: 5px;
        }
      }
    }
  }
  .card-title{
    position: absolute;
    top: 0;
    left: 0;
    padding: 5px;
    font-weight: bold;
    font-size: 18px;
  }
  :deep(.el-form-item__label){
    font-size: 16px;
  }
  :deep(.el-form-item__content){
    font-size: 16px !important;
  }
}
.auto-box{
  height: calc(80vh - 290px);
  overflow: auto;
  margin-top: 20px;
}
:deep(.el-input-number__increase){
  background: rgb(235.9, 245.3, 255);
}
:deep(.el-input-number__decrease){
  background: rgb(235.9, 245.3, 255);
}
:deep(.el-input-number){
  width: 100%;
}
:deep(.el-tag){
  font-size: 15px;
}
.truncate-text{
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-card){
  overflow: hidden !important;
}

.wait-delivery-dialog{
  // min-width: 1300px;
  // box-sizing: border-box;
}
</style>
